package com.yangyang.notepad;

import android.Manifest;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.Navigation;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.appbar.MaterialToolbar;
import com.google.android.material.dialog.MaterialAlertDialogBuilder;
import com.google.android.material.floatingactionbutton.FloatingActionButton;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import it.xabaras.android.recyclerview.swipedecorator.RecyclerViewSwipeDecorator;

public class MainFragment extends Fragment {
    private NoteDatabaseHelper databaseHelper;
    private RecyclerView notesRecyclerView;
    private NoteAdapter noteAdapter;
    private List<Note> notes = new ArrayList<>();
    private SharedViewModel viewModel;
    //private ExtendedFloatingActionButton fab;
    private FloatingActionButton fab;
    private ClipboardManager clipboardManager;

    private static final int REQUEST_IMPORT_FILE = 1001;
    private static final int REQUEST_READ_EXTERNAL_STORAGE = 1002;
    // 在类顶部添加
    //private ExcelHelper excelHelper;

    //创建并返回 Fragment 的视图层级
    //在 onCreate() 之后
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 初始化数据库
        databaseHelper = new NoteDatabaseHelper(getContext());
        //excelHelper = new ExcelHelper(requireContext(), databaseHelper);

        View view = inflater.inflate(R.layout.fragment_main, container, false);
        clipboardManager = (ClipboardManager) requireActivity().getSystemService(Context.CLIPBOARD_SERVICE);

        // 初始化 RecyclerView
        notesRecyclerView = view.findViewById(R.id.notesRecyclerView);
        notesRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        // 初始化 Adapter
        noteAdapter = new NoteAdapter(notes, new NoteAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(Note note) {
                // 点击便签，跳转到编辑页面
                Bundle bundle = new Bundle();
                bundle.putParcelable("note", note);
                Navigation.findNavController(view).navigate(R.id.action_mainFragment_to_editNoteFragment, bundle);
            }

            @Override
            public void onItemLongClick(Note note) {
                // 长按删除
                new AlertDialog.Builder(requireContext())
                        .setTitle("删除笔记")
                        .setMessage("确定要删除这条笔记吗？")
                        .setPositiveButton("删除", (dialog, which) -> {
                            databaseHelper.deleteNote(note.getId());
                            loadNotesFromDatabase();
                        })
                        .setNegativeButton("取消", null)
                        .show();
            }
        });
        notesRecyclerView.setAdapter(noteAdapter);

        // 加载便签数据
        //loadNotes();

        // 修改加载笔记方法
        loadNotesFromDatabase();


        // 绑定按钮点击事件
//        MaterialButton btnAdd = view.findViewById(R.id.btn_add);
//        MaterialButton btnPaste = view.findViewById(R.id.btn_paste);
//        MaterialButton btnSettings = view.findViewById(R.id.btn_settings);

//        btnAdd.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                // 新增功能 - 与FAB相同
//                Navigation.findNavController(view).navigate(R.id.action_mainFragment_to_editNoteFragment);
//            }
//        });
//
//        btnPaste.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                handlePaste(view);
//            }
//        });
//
//        btnSettings.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                // 设置功能 - 暂时只显示Toast
//                Toast.makeText(getActivity(), "设置功能待实现", Toast.LENGTH_SHORT).show();
//
//                //TODO 1 测试刷新列表
//                loadNotesFromDatabase();
//            }
//        });


        return view;
    }

    private void handlePaste(View view) {
        // 粘贴功能 - 检查剪贴板是否有内容
        if (clipboardManager.hasPrimaryClip()) {
            ClipData.Item item = clipboardManager.getPrimaryClip().getItemAt(0);
            String clipboardText = item.getText().toString();

            // 创建新笔记并传递剪贴板内容，明确设置ID为-1表示新笔记
            Note newNote = new Note("", clipboardText);
            newNote.setId(null);  // 明确标识这是一个新笔记
            Bundle bundle = new Bundle();
            bundle.putParcelable("note", newNote);
            //bundle.putBoolean("isNewNote", true); // 显式标记为新笔记
            Navigation.findNavController(view).navigate(R.id.action_mainFragment_to_editNoteFragment, bundle);
        } else {
            Toast.makeText(getActivity(), "剪贴板为空", Toast.LENGTH_SHORT).show();
        }
    }

//    private void loadNotes() {
//        // 从数据库或网络加载便签数据
//        notes.clear();
//        notes.addAll(getSampleNotes()); // 示例数据
//        noteAdapter.notifyDataSetChanged();
//    }

    private void loadNotesFromDatabase() {
        notes.clear();
        notes.addAll(databaseHelper.getAllNotes());
        noteAdapter.notifyDataSetChanged();
    }


//    private List<Note> getSampleNotes() {
//        List<Note> sampleNotes = new ArrayList<>();
//        sampleNotes.add(new Note("标题1", "内容1"));
//        sampleNotes.add(new Note("标题2", "内容2"));
//
//        for (int i = 3; i <= 20; i++) {
//            sampleNotes.add(new Note("标题" + i, "内容" + i));
//        }
//
//        return sampleNotes;
//    }

    //在视图创建完成后初始化控件和逻辑
    //在 onCreateView() 之后
    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        MaterialToolbar toolbar = view.findViewById(R.id.toolbar);
        toolbar.setNavigationOnClickListener(v -> {
            Navigation.findNavController(view).navigateUp();
        });

        // 设置菜单点击监听
        toolbar.setOnMenuItemClickListener(item -> {
            int id = item.getItemId();


            if (id == R.id.menu_add) {
                // 新增功能 - 与FAB相同
                Navigation.findNavController(view).navigate(R.id.action_mainFragment_to_editNoteFragment);
                return true;
            }
            if (id == R.id.menu_paste) {
                handlePaste(view);
                return true;
            }
            if (id == R.id.menu_settings) {
                // 设置功能 - 暂时只显示Toast
                Toast.makeText(getActivity(), "设置功能待实现", Toast.LENGTH_SHORT).show();
                //TODO 1 测试刷新列表
                loadNotesFromDatabase();
                return true;
            }

            if (id == R.id.menu_import) {
                importFromExcel();
                return true;
            }
            if (id == R.id.menu_export) {
                exportToExcel();
                //excelHelper.exportNotes();
                //Toast.makeText(requireContext(), "导出", Toast.LENGTH_SHORT).show();
                return true;
            }

//            if (id == R.id.menu_import_db) {
//                importFromDB();
//                return true;
//            }
            if (id == R.id.menu_export_db) {
                exportToDB();
                return true;
            }

            return false;
        });

        // 初始化ViewModel（与Activity共享）
        viewModel = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);

        // 绑定FAB
        fab = view.findViewById(R.id.fab);
        fab.setOnClickListener(v -> {
            // 点击事件处理
            Navigation.findNavController(v).navigate(R.id.action_mainFragment_to_editNoteFragment);
        });

        // 观察Visibility变化
        viewModel.getFabVisibility().observe(getViewLifecycleOwner(), visible -> {
            fab.setVisibility(visible ? View.VISIBLE : View.GONE);
        });


        // 在 MainFragment 的 onViewCreated 方法中添加：
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(
                0, // 拖拽方向（0表示禁用拖拽）
                ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT // 允许左右滑动
        ) {
            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false; // 禁用拖拽排序
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                int position = viewHolder.getAdapterPosition();
                if (position == RecyclerView.NO_POSITION) return; // 防止无效 position

                // 先获取数据，再删除
                long noteId = noteAdapter.getNoteId(position); // 先获取 ID
                //Note note = noteAdapter.getNote(position);     // 先获取 Note 对象

                if (direction == ItemTouchHelper.LEFT) {
                    // 左滑删除
                    // 显示确认对话框
                    new MaterialAlertDialogBuilder(requireContext())
                            .setTitle("删除笔记")
                            .setMessage("确定要永久删除这条笔记吗？")
                            .setPositiveButton("删除", (dialog, which) -> {
                                // 执行物理删除
                                databaseHelper.deleteNote(noteId);
                                noteAdapter.deleteNote(position);
                                Toast.makeText(getContext(), "笔记已删除", Toast.LENGTH_SHORT).show();
                            })
                            .setNegativeButton("取消", (dialog, which) -> {
                                // 取消删除，恢复item状态
                                noteAdapter.notifyItemChanged(position);
                            })
                            .setCancelable(false)
                            .show();
//                    databaseHelper.deleteNote(noteId); // 先删除数据库
//                    noteAdapter.deleteNote(position);  // 再删除列表数据
                } else if (direction == ItemTouchHelper.RIGHT) {
                    // 右滑归档
                    databaseHelper.archiveNote(noteId); // 先更新数据库
                    noteAdapter.archiveNote(position);  // 再更新列表数据
                }
            }

            // 可选：设置滑动时的背景色和图标
            @Override
            public void onChildDraw(@NonNull Canvas c, @NonNull RecyclerView recyclerView,
                                    @NonNull RecyclerView.ViewHolder viewHolder,
                                    float dX, float dY, int actionState, boolean isCurrentlyActive) {
                // 自定义滑动时的UI效果（例如显示红色背景+删除图标）
                new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
                        .addSwipeLeftBackgroundColor(ContextCompat.getColor(requireContext(), R.color.delete_red))
                        .addSwipeLeftActionIcon(R.drawable.baseline_delete_24)
                        .addSwipeRightBackgroundColor(ContextCompat.getColor(requireContext(), R.color.archive_green))
                        .addSwipeRightActionIcon(R.drawable.baseline_archive_24)
                        .create()
                        .decorate();
                super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
            }
        });

        // 绑定到 RecyclerView
        itemTouchHelper.attachToRecyclerView(notesRecyclerView);
    }

    private void importFromDB() {
        DatabaseBackupHelperOptimized backupHelper = new DatabaseBackupHelperOptimized();
        //DatabaseBackupHelper backupHelper = new DatabaseBackupHelper();
    }

    private void exportToDB() {
        DatabaseBackupHelperOptimized backupHelper = new DatabaseBackupHelperOptimized();
        //DatabaseBackupHelper backupHelper = new DatabaseBackupHelper();
        backupHelper.exportDatabase(requireContext(), NoteDatabaseHelper.DATABASE_NAME);
    }


    private void importFromExcel() {
        // 请求文件读取权限
        if (ContextCompat.checkSelfPermission(requireContext(), Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXTERNAL_STORAGE);
            return;
        }

        // 启动文件选择器
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("*/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, REQUEST_IMPORT_FILE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == REQUEST_IMPORT_FILE && resultCode == Activity.RESULT_OK && data != null) {
            Uri uri = data.getData();
            if (uri != null) {
                //excelHelper.importNotes(uri);
                importExcelFile(uri);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_READ_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                importFromExcel();
            } else {
                Toast.makeText(getContext(), "需要存储权限才能导入文件", Toast.LENGTH_SHORT).show();
            }
        }
    }


    /**
     * 导出
     */
    private void exportToExcel() {
        // 获取所有笔记
        List<Note> notes = databaseHelper.getAllNotes();

        // 反转列表顺序
        Collections.reverse(notes);

        // 创建Excel工作簿
        //Workbook workbook = new XSSFWorkbook();
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("Notes");

        // 创建标题行
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("ID");
        headerRow.createCell(1).setCellValue("Title");
        headerRow.createCell(2).setCellValue("Content");
        headerRow.createCell(3).setCellValue("Create Time");
        headerRow.createCell(4).setCellValue("Update Time");

        // 填充数据
        for (int i = 0; i < notes.size(); i++) {
            Note note = notes.get(i);
            Row row = sheet.createRow(i + 1);

            row.createCell(0).setCellValue(note.getId());
            row.createCell(1).setCellValue(note.getTitle());
            row.createCell(2).setCellValue(note.getContent());
            row.createCell(3).setCellValue(DateUtil.longFormatTime(note.getCreateTime()));
            row.createCell(4).setCellValue(DateUtil.longFormatTime(note.getUpdateTime()));
        }

        // 保存文件
        try {
            // 创建导出目录
            File exportDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS), "Notepad Exports");
            if (!exportDir.exists()) {
                exportDir.mkdirs();
            }

            // 生成文件名
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault());
            String fileName = "notes_export_" + sdf.format(new Date()) + ".xls";
            File file = new File(exportDir, fileName);

            // 写入文件
            FileOutputStream outputStream = new FileOutputStream(file);
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();

            // 通知用户
            Toast.makeText(getContext(), "导出成功: " + file.getAbsolutePath(), Toast.LENGTH_LONG).show();

            // 发送广播让系统扫描新文件
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            mediaScanIntent.setData(Uri.fromFile(file));
            requireActivity().sendBroadcast(mediaScanIntent);

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "导出失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }


    /**
     * 导入
     *
     * @param uri
     */
    private void importExcelFile(Uri uri) {
        try {
            InputStream inputStream = requireActivity().getContentResolver().openInputStream(uri);
            //Workbook workbook = new XSSFWorkbook(inputStream);
            Workbook workbook = new HSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);

            int importedCount = 0;
            int skippedCount = 0;

            // 从第二行开始读取数据（跳过标题行）
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                try {
                    String idValue = getCellStringValue(row.getCell(0));
                    Long parseId = StringUtils.isBlank(idValue) ? null : Long.parseLong(idValue);

                    Note note = new Note(getCellStringValue(row.getCell(1)), // title
                            getCellStringValue(row.getCell(2))  // content
                    );

                    // 设置创建时间和更新时间
                    String createTimeStr = getCellStringValue(row.getCell(3));
                    String updateTimeStr = getCellStringValue(row.getCell(4));

                    if (!createTimeStr.isEmpty()) {
                        note.setCreateTime(DateUtil.timeStrToLong(createTimeStr));
                    }

                    if (!updateTimeStr.isEmpty()) {
                        note.setUpdateTime(DateUtil.timeStrToLong(updateTimeStr));
                    }

                    //删除原有的数据
                    if (parseId != null && databaseHelper.getNote(parseId) != null) {
                        note.setId(parseId);
                        databaseHelper.deleteNote(parseId);
                    }

                    // 添加到数据库
                    databaseHelper.importNoteWithTimestamps(note);
                    importedCount++;

                } catch (Exception e) {
                    e.printStackTrace();
                    skippedCount++;
                }
            }

            workbook.close();
            inputStream.close();

            // 刷新列表
            loadNotesFromDatabase();

            // 显示结果
            Toast.makeText(getContext(), "导入完成: " + importedCount + "条成功, " + skippedCount + "条跳过", Toast.LENGTH_LONG).show();

        } catch (Exception e) {
            e.printStackTrace();
            Toast.makeText(getContext(), "导入失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private String getCellStringValue(Cell cell) {
        if (cell == null) return "";
        DataFormatter formatter = new DataFormatter();
        return formatter.formatCellValue(cell);
    }

}
